package com.lfs.market.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.lfs.market.exception.ServiceException;
import com.lfs.market.manager.AiManager;
import com.lfs.market.model.enums.ResultCode;
import com.lfs.market.service.AIChatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

import static com.lfs.market.constants.AIPrompt.AIPrompt;


@Slf4j
@Service
public class AIChatServiceImpl implements AIChatService {
    @Resource
    private AiManager aiManager;

    /**
     * ai聊天接口
     *
     * @param message
     * @return
     */
    @Override
    public String sendChat(String message) {
        String resultString = "系统繁忙，请稍后！";
        if (BeanUtil.isEmpty(message)) {
            return "发送消息为空";
        }
        String result = aiManager.doSyncRequest(AIPrompt, message, null);
        log.info(result + "====================================================================");
        if (!result.contains("[{message") ||
                !result.contains("[{\"message") ||
                !result.contains("```json")) {
            return result;
        } else {
            try {
                int start = result.indexOf("[");
                int end = result.lastIndexOf("]");
                String json = result.substring(start, end + 1);
                List<String> jsonObjects = new ArrayList<>();
                JSONArray jsonArray = JSONUtil.parseArray(json);
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    String messageStr = jsonObject.getStr("message");
                    jsonObjects.add(messageStr);
                }
                // 从 JSONObject 中提取 "message" 字段的值
                resultString = String.join("", jsonObjects);
            } catch (Exception e) {
                throw new ServiceException(ResultCode.Fail, "系统繁忙，请稍后！");
            }
        }
        return resultString;
    }
}
